package models

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"fmt"
)

var (
	_db *sql.DB
	_tx *sql.Tx
	_isTransaction bool = false
)

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
		panic(err)
	}
}

func Connect(filepath string) (error) {
	var _err error
	_db, _err = sql.Open("sqlite3", filepath)
	checkErr(_err)

	_err = _db.Ping()
	checkErr(_err)
	return _err
}

func Query(sql string) (*sql.Rows, error){
	rows, _err := _db.Query(sql)
	checkErr(_err)
	return rows, _err
}

func Exec(sql string) error {
	if _isTransaction {
		_, _err := _tx.Exec(sql)
		checkErr(_err)
		return _err
	}
	_, _err := _db.Exec(sql)
	checkErr(_err)
	return _err
	
}

func Close() {
	_db.Close()
}

func BeginTx() error{
	_tx, _err := _db.Begin()
	fmt.Println(_tx)

	checkErr(_err)
	_isTransaction = true
	return _err
}

func Rollback() error {
	_err := _tx.Rollback()
	checkErr(_err)
	_isTransaction = false
	return _err
}

func Commit() error {
	_err := _tx.Commit()
	checkErr(_err)
	_isTransaction = false
	return _err
}


